﻿using System.Text.Json;
using TodayApp.Models;

namespace TodayApp.Services;

public class TodayImageService : ITodayImageService {
    private readonly IAlertService _alertService;

    public TodayImageService(IAlertService alertService) {
        _alertService = alertService ??
            throw new ArgumentNullException(nameof(alertService));
    }

    public async Task<TodayImage> GetTodayImageAsync() {
        var httpClient = new HttpClient();

        HttpResponseMessage response;
        try {
            response = await httpClient.GetAsync(
                "https://www.bing.com/HPImageArchive.aspx?format=js&idx=0&n=1&mkt=zh-CN");
            response.EnsureSuccessStatusCode();
        } catch (Exception e) {
            _alertService.Alert(e.Message);
            return new TodayImage();
        }

        var json = await response.Content.ReadAsStringAsync();
        var bingObject = JsonSerializer.Deserialize<Bing>(json);
        var url = "https://www.bing.com" + bingObject.images.First().url;

        try {
            response = await httpClient.GetAsync(url);
            response.EnsureSuccessStatusCode();
        } catch (Exception e) {
            _alertService.Alert(e.Message);
            return new TodayImage();
        }

        return new TodayImage {
            ImageBytes = await response.Content.ReadAsByteArrayAsync()
        };
    }
}

public class Bing {
    public Image[] images { get; set; }
}

public class Image {
    public string url { get; set; }
}